package com.wizinno.android.urineflow.util;

import com.alibaba.fastjson.JSON;
import com.wizinno.android.urineflow.bean.Device;
import com.wizinno.android.urineflow.bean.ServerResult;
import com.wizinno.android.urineflow.constant.CommonControl;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * @author LiuMei
 * @date 2020-11-19.
 */
public class ServerUtil {
    private final static String TAG = "ServerUtil";
    public static final String URL = "http://10.68.170.134:8080/urineflow/api/android/device/"+ CommonControl.INSTANCE.DEVICE_SN;
    public static Device getDeviceInfo() {
        Device device = new Device();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(URL).get().build();
        Call call = client.newCall(request);
        //通过execute()方法获得请求响应的Response对象
        Response response;
        try {
            response = call.execute();
            if (response.isSuccessful()) {
                String result = response.body().string();
                ServerResult serverResult = getServerResult(result);
                Integer code = serverResult.getCode();
                if (code == 0) {
                    String deviceStr = JSON.toJSONString(serverResult.getResult());
                    device = JSON.parseObject(deviceStr, Device.class);
                } else {
                    String message = serverResult.getMessage();
                    String errorInfo = message ==null?serverResult.getData(): message;
                    LogUtils.e(errorInfo);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return device;
    }

    private static ServerResult getServerResult(String result) {
        return JSON.parseObject(result, ServerResult.class);
    }
}
